package com.ct.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.ct.entity.enums.PageSize;
import com.ct.entity.enums.ReimbursementApprovalEnum;
import com.ct.entity.po.Approval;
import com.ct.entity.po.Reimbursement;
import com.ct.entity.po.ReimbursementApprovalMa;
import com.ct.entity.po.Travel;
import com.ct.entity.po.User;
import com.ct.entity.query.ApprovalQuery;
import com.ct.entity.query.ReimbursementApprovalMaQuery;
import com.ct.entity.query.SimplePage;
import com.ct.entity.vo.PaginationResultVO;
import com.ct.entity.vo.ReimbursementVO;
import com.ct.mappers.ApprovalMapper;
import com.ct.mappers.ReimbursementApprovalMaMapper;
import com.ct.service.ReimbursementApprovalMaService;
import com.ct.service.client.ReimbursementClient;
import com.ct.service.client.TravelClient;
import com.ct.service.client.UserClient;
import com.ct.utils.CopyTools;
import com.ct.utils.StringTools;

import jakarta.annotation.Resource;

/**
 * 经理审批报销申请记录 业务接口实现
 */
@Service("reimbursementApprovalMaService")
public class ReimbursementApprovalMaServiceImpl implements ReimbursementApprovalMaService {

    @Resource
    private ReimbursementApprovalMaMapper<ReimbursementApprovalMa, ReimbursementApprovalMaQuery> reimbursementApprovalMaMapper;

    @Resource
    private ReimbursementClient reimbursementClient;

    @Resource
    private TravelClient travelClient;

    @Resource
    private UserClient userClient;

    @Resource
    private ApprovalMapper<Approval, ApprovalQuery> approvalMapper;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<ReimbursementApprovalMa> findListByParam(ReimbursementApprovalMaQuery param) {
        return this.reimbursementApprovalMaMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(ReimbursementApprovalMaQuery param) {
        return this.reimbursementApprovalMaMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<ReimbursementApprovalMa> findListByPage(ReimbursementApprovalMaQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<ReimbursementApprovalMa> list = this.findListByParam(param);
        PaginationResultVO<ReimbursementApprovalMa> result = new PaginationResultVO<>(count, page.getPageSize(),
                page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(ReimbursementApprovalMa bean) {
        return this.reimbursementApprovalMaMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<ReimbursementApprovalMa> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.reimbursementApprovalMaMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<ReimbursementApprovalMa> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.reimbursementApprovalMaMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(ReimbursementApprovalMa bean, ReimbursementApprovalMaQuery param) {
        StringTools.checkParam(param);
        return this.reimbursementApprovalMaMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(ReimbursementApprovalMaQuery param) {
        StringTools.checkParam(param);
        return this.reimbursementApprovalMaMapper.deleteByParam(param);
    }

    /**
     * 根据ReimbursementApprovalMaId获取对象
     */
    @Override
    public ReimbursementApprovalMa getReimbursementApprovalMaByReimbursementApprovalMaId(
            Integer reimbursementApprovalMaId) {
        return this.reimbursementApprovalMaMapper.selectByReimbursementApprovalMaId(reimbursementApprovalMaId);
    }

    /**
     * 根据ReimbursementApprovalMaId修改
     */
    @Override
    public Integer updateReimbursementApprovalMaByReimbursementApprovalMaId(ReimbursementApprovalMa bean,
            Integer reimbursementApprovalMaId) {
        return this.reimbursementApprovalMaMapper.updateByReimbursementApprovalMaId(bean, reimbursementApprovalMaId);
    }

    /**
     * 根据ReimbursementApprovalMaId删除
     */
    @Override
    public Integer deleteReimbursementApprovalMaByReimbursementApprovalMaId(Integer reimbursementApprovalMaId) {
        return this.reimbursementApprovalMaMapper.deleteByReimbursementApprovalMaId(reimbursementApprovalMaId);
    }

    @Override
    public PaginationResultVO<ReimbursementVO> getApproveReimbursementRecordMa(String userId, Integer pageNo,
            Integer pageSize) {
        List<ReimbursementVO> reimbursementVOList = new ArrayList<>();
        // 查询所有已审批的报销申请记录
        ReimbursementApprovalMaQuery query = new ReimbursementApprovalMaQuery();
        query.setManagerId(userId);
        List<ReimbursementApprovalMa> reimbursementApprovalMaList = this.findListByParam(query);

        if (reimbursementApprovalMaList == null || reimbursementApprovalMaList.isEmpty()) {
            return null;
        }

        // 获取报销申请信息
        List<Integer> reimbursementIdList = reimbursementApprovalMaList.stream()
                .map(ReimbursementApprovalMa::getReimbursementId)
                .distinct().toList();
        List<Reimbursement> reimbursementList = this.reimbursementClient
                .getReimbursementByTravelIdList(reimbursementIdList);

        // 获取出差信息
        List<Integer> travelIdList = reimbursementList.stream().map(Reimbursement::getTravelId).distinct().toList();
        List<Travel> travelList = this.travelClient.getAllTravelsByIdList(travelIdList);
        Map<Integer, Travel> travelMap = travelList.stream()
                .collect(Collectors.toMap(Travel::getTravelId, travel -> travel));

        // 获取用户信息
        List<String> userIdList = travelList.stream().map(Travel::getUserId).distinct().toList();
        List<User> userList = userClient.getAllUsersByIdList(userIdList);
        Map<String, User> userMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, user -> user));

        for (Reimbursement reimbursement : reimbursementList) {
            ReimbursementVO reimbursementVO = CopyTools.copy(reimbursement, ReimbursementVO.class);
            reimbursementVO.setReimbursement(reimbursement.getFoodCost().add(reimbursement.getHotelCost())
                    .add(reimbursement.getTransportCost()));

            Travel travel = travelMap.get(reimbursement.getTravelId());
            reimbursementVO.setTravelReason(travel.getTravelReason());
            reimbursementVO.setTravelDetail(travel.getTravelDetail());
            reimbursementVO.setStartDate(travel.getStartDate());
            reimbursementVO.setEndDate(travel.getEndDate());

            User user = userMap.get(travel.getUserId());
            reimbursementVO.setUserId(user.getUserId());
            reimbursementVO.setUserName(user.getName());
            reimbursementVO.setUserPhone(user.getPhone());
            reimbursementVO.setUserEmail(user.getEmail());
            reimbursementVO.setPosition(user.getPosition());

            ApprovalQuery approvalQuery = new ApprovalQuery();
            approvalQuery.setTravelId(reimbursement.getTravelId());

            Approval approval = approvalMapper.selectList(approvalQuery).get(0);
            reimbursementVO.setApprovalId(approval.getApprovalId());
            reimbursementVO.setReimbursementStatus(approval.getReimbursementApprovalMa().toString());
            reimbursementVO.setReimbursementStatusName(
                    ReimbursementApprovalEnum.getByType(approval.getReimbursementApprovalMa()).getDesc());
            reimbursementVO.setReimbursementRejection(approval.getReimbursementRejectionMa());

            reimbursementVOList.add(reimbursementVO);
        }

        int count = reimbursementVOList.size();
        int start = (pageNo - 1) * pageSize;
        int end = start + pageSize;
        if (end > count) {
            end = count;
        }
        int totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;

        PaginationResultVO<ReimbursementVO> result = new PaginationResultVO<>(count, pageSize, pageNo, totalPage,
                reimbursementVOList);

        return result;
    }

    @Override
    public ReimbursementApprovalMa getReimbursementApprovalMaByReimbursementId(Integer reimbursementId) {
        return this.reimbursementApprovalMaMapper.selectByReimbursementId(reimbursementId);
    }

}